package com.mic.nio;

import com.mic.nio.pool.Boss;
import com.mic.nio.pool.NioSelectorRunnablePool;
import com.mic.nio.pool.Worker;

import java.io.IOException;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;

import static java.lang.System.out;

/**
 * Created by yjq14 on 2018/2/10.
 */
public class NioServerBoss extends AbstractNioSelector implements Boss{
    public  NioServerBoss(Executor executor, String threadName, NioSelectorRunnablePool nioSelectorRunnablePool) {
        super(executor, threadName, nioSelectorRunnablePool);
    }

    @Override
    protected int select(Selector selector) throws IOException {
        return selector.select();
    }

    @Override
    protected void process(Selector selector) throws IOException {
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        if (selectionKeys.isEmpty()) return;
        for (Iterator<SelectionKey> iterator = selectionKeys.iterator(); iterator.hasNext();) {
            SelectionKey key = iterator.next();
            iterator.remove();
            ServerSocketChannel server = (ServerSocketChannel) key.channel();
            SocketChannel channel = server.accept();
            channel.configureBlocking(false);
            Worker worker = getNioSelectorRunnablePool().nextWorker();
            worker.registerNewChannelTask(channel);
            out.println("新客户连接");
        }
    }

    @Override
    public void registerAcceptChannelTask(ServerSocketChannel serverChannel) {
        final Selector selector = this.selector;
        registerTask(() -> {
            try {
                serverChannel.register(selector, SelectionKey.OP_ACCEPT);
            } catch (ClosedChannelException e) {
                e.printStackTrace();
            }
        });
    }
}
